#!/usr/bin/env python3
"""
Agent HTTP API服务器
"""

from flask import Flask, request, jsonify
from tools import execute_job_function, get_system_info
import threading
import logging

logger = logging.getLogger(__name__)

app = Flask(__name__)

class AgentAPIServer:
    def __init__(self, agent_instance, port=8888):
        self.agent = agent_instance
        self.port = port
        self.server_thread = None
        
    def start_server(self):
        """启动HTTP服务器"""
        self.server_thread = threading.Thread(
            target=lambda: app.run(host='0.0.0.0', port=self.port, debug=False),
            daemon=True
        )
        self.server_thread.start()
        logger.info("HTTP API服务器已启动，端口: {}".format(self.port))

# API路由定义
@app.route('/health', methods=['GET'])
def health_check():
    """健康检查"""
    return jsonify({
        'status': 'ok',
        'message': 'Agent is running'
    })

@app.route('/agent/info', methods=['GET'])
def get_agent_info():
    """获取Agent信息"""
    return jsonify({
        'agent_id': app.agent.agent_id if hasattr(app, 'agent') else 'unknown',
        'status': 'running',
        'server_url': app.agent.base_url if hasattr(app, 'agent') else 'unknown'
    })

@app.route('/system/info', methods=['GET'])
def get_system_info_api():
    """获取系统信息"""
    try:
        system_info = get_system_info()
        if system_info:
            return jsonify({
                'status': 'success',
                'data': system_info
            })
        else:
            return jsonify({
                'status': 'error',
                'message': '无法获取系统信息'
            }), 500
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@app.route('/execute', methods=['POST'])
def execute_function():
    """执行指定的方法"""
    try:
        job_data = request.get_json()
        if not job_data:
            return jsonify({
                'status': 'error',
                'message': '请求数据为空'
            }), 400
            
        # 执行方法
        result = execute_job_function(job_data)
        
        return jsonify({
            'status': 'success',
            'data': result
        })
        
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@app.route('/telnet', methods=['POST'])
def telnet_test():
    """Telnet测试接口"""
    try:
        data = request.get_json()
        job_data = {
            'fun_name': 'fun_telnet',
            'url': data.get('url'),
            'port': data.get('port', 23)
        }
        
        result = execute_job_function(job_data)
        return jsonify(result)
        
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@app.route('/curl', methods=['POST'])
def curl_test():
    """Curl测试接口"""
    try:
        data = request.get_json()
        job_data = {
            'fun_name': 'fun_curl',
            'url': data.get('url')
        }
        
        result = execute_job_function(job_data)
        return jsonify(result)
        
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

# 设置agent实例的辅助函数
def set_agent_instance(agent_instance):
    """设置agent实例到Flask app"""
    app.agent = agent_instance